<?php
/*
 * @Author: LDY dong2406@126.com
 * @Date: 2022-09-14 10:32:58
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2022-10-30 15:30:19
 */

namespace Ldy\Models;

use Ldy\Model;
use Ldy\Traits\Model\Trees;
use Casbin\WebmanPermission\Permission;

class SysApi extends Model{
    
	use Trees;

	/**
	 * 更新之前删除所有角色拥有该api的授权规则
	 *
	 * @param [type] $model
	 * @return void
	 */
	public static function onBeforeUpdate($model){
		$id = $model->id;
		$role_api = self::getRoleApi($id);
		if(!empty($role_api)){
			foreach($role_api as $item){
				$roleName = casbin_role_field_prefix($item->role_id);
				Permission::deletePermissionForUser($roleName, $item->path,$item->action);
			}
		}
	}

	/**
	 * 添加api更新后的权限规则
	 *
	 * @param [type] $model
	 * @return void
	 */
	public static function onAfterUpdate($model){

		$id = $model->id;
		$newPath = $model->path;
		$newAction = $model->action;

		if(empty($id) || empty($newPath)) return false;

		//找出那些角色使用了这条权限规则
		$role_api = self::getRoleApi($id);

		if($role_api->isEmpty()) return false;

		$addRules = [];
		foreach($role_api as $item){
			$roleName = casbin_role_field_prefix($item->role_id);
			$addRules[] = [$roleName, $newPath, $newAction];
		}

		Permission::addPolicies($addRules);
	}

	/**
	 * 删除api 关联删除角色中的规则
	 *
	 * @param [type] $id
	 * @return void
	 */
	public static function delApi($id){
		$role_api = self::getRoleApi($id);
		foreach($role_api as $item){
			$roleName = casbin_role_field_prefix($item->role_id);
			Permission::deletePermissionForUser($roleName, $item->path, $item->action);
		}
	}

	/**
	 * 根据api id 找出那些角色使用了这条权限规则
	 *
	 * @param [type] $id 接口ID
	 * @return Object
	 */
	public static function getRoleApi($id){

		$dbData = self::alias('a')
		->field('a.path,rm.role_id,a.action')
		->join('sys_menu_api ma', 'a.id=ma.api_id')
		->join('sys_role_menu rm','rm.menu_id=ma.menu_id')
		->where('a.id', $id)
		->select();

		return $dbData;
	}
}